<?php

/*
 * Created on 2013-1-16
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
set_time_limit(0);
if (!isset($_FILES['Filedata'])) {
        exit('FILES 不存在');
}
if($_FILES['Filedata']['error']>0){
exit('上传错误码：'.$_FILES['Filedata']['error']);
}
/** MGTV节目单导入主体方法
 * @param String 
 * @return 错误描述
 * 			成功为"success"
 */
function mgtv_import_playbill() {
        $fileParts = pathinfo($_FILES['Filedata']['name']);

        if (strtolower($fileParts['extension']) == 'txt') {
//		导入文件为TXT 则调用TXT解析
                $state = mgtv_import_playbill_by_txt();
        } elseif (strtolower($fileParts['extension']) == 'xls') {
//		导入文件为EXCEL 则调用EXCEL解析
                $state = mgtv_import_playbill_by_excel();
        } else {
                $state = 'Error';
        }

        return $state;
}

/* * 解析TXT并写入数据库的方法的方法写这里。。。。* */

function mgtv_import_playbill_by_txt() {
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $fileArr = file($tempFile);
		//error_log($tempFile."\n",'3','E:\test.txt');
		//error_log(var_export($fileArr,true)."\n",'3','E:\test.txt');
        $Channel = trim(str_replace('Channel:', '', array_shift($fileArr))); //Channel:CCTV-1
        $list = array();
        $deltime = array();
        $key = '';
        foreach ($fileArr as $v) {
                if (empty($v))
                        continue;
                if (strripos($v, 'Date:') === 0) {
                        $key = trim(substr($v, "5"));
                        $deltime[] = $key;
                        continue;
                }
                preg_match('/(?P<startime>\w+)-(?P<endtime>\w+)\|(?P<name>.*)/i', $v, $text);
                $addarr = array();				
				$is_utf8 = @is_utf8($text['name']);
				if($is_utf8===false){
					$name = @iconv('gbk', 'utf-8', $text['name']);
				}else{
					$name = $text['name'];
				}
                
                $addarr['name'] = $name;
                $addarr['pinyin']=nns_controls_pinyin_class::get_pinyin_letter($addarr['name']);
                $startime = @strtotime($key . $text['startime']);
                $endtime = @strtotime($key . $text['endtime']);
                $addarr['begin_time'] = date('Y-m-d H:i:s', $startime);
                $addarr['time_len'] = ($startime > $endtime ? $endtime + 86400 : $endtime) - $startime;
                $list[] = $addarr;
        }
		//error_log(var_export($list,true)."\n",'3','E:\test.txt');
        $result = mgtv_add_playbill($list, $deltime);
        return $result;
}



function is_utf8($word)
{
	if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/* * 解析EXCEL的方法并写入数据库的方法写这里。。。。* */

function mgtv_import_playbill_by_excel() {
        require_once dirname(dirname(dirname(__FILE__))) . '/models/excel_reader/reader.php';
        $excel_reader = new Spreadsheet_Excel_Reader();
        $excel_reader->setOutputEncoding('utf-8'); //CP936
        $excel_reader->setRowColOffset(0);
        $excel_reader->read($_FILES['Filedata']['tmp_name']);
        $count_sheetData = count($excel_reader->sheets[0]['numRows']);
        $list = $excel_reader->sheets[0]['cells'];
        $result = array();
        $deltime = array();
        foreach ($list as $v) {
        		if(empty($v)){
        			continue;
        		}
                $begin_time = str_replace('.', '-', $v[1]); //2013.03.29 19:30:00
                $addarr = array();
                $deltime[] = date('Ymd', strtotime($begin_time));
				
                $addarr['name'] = $v[0];
                $addarr['pinyin']=nns_controls_pinyin_class::get_pinyin_letter($addarr['name']);
                $addarr['begin_time'] = $begin_time;
                $addarr['time_len'] = strtotime(str_replace('.', '-', $v[2])) - strtotime($begin_time);
                $result[] = $addarr;
        }
        $deltime = array_unique($deltime);
        $result = mgtv_add_playbill($result, $deltime);
        return $result;
}

/*
 * 根据导入数据 写入数据库
 */

function mgtv_add_playbill($list, $deltime) {
        if (!is_array($list) || !is_array($deltime)) {
	        echo '数据为空';
                return false;
        }
        set_time_limit(0);

        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $dc->open();
        $file_name = $_FILES['Filedata']['name'];
        $file_info = explode('__', $file_name);
        $pro_id = $file_info[0];
        $live_list = nl_live_bo::get_video_ids_by_pid($dc->db(), $pro_id);

        /*
          if ($live_list===FALSE || $live_list===TRUE) { 判断语句有误。。。。
          return '该频道不存在！';
          } */
        if (!is_array($live_list) || empty($pro_id)) {
                return '该频道不存在！';
        }
        $resultnum = 0;
		/*
        foreach ($live_list as $live_item) {
        		if($g_inject){
					$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
					$xml_str .= '<Objects>';
				}
                $video_id = $live_item['nns_live_id'];
				error_log("=============5===========\n",'3','test.txt');
				error_log(var_export($live_item,true)."\n",'3','test.txt');
                foreach ($deltime as $dt) {
                        $endtime = date('Ymd', strtotime($dt) + 86400);
                        nl_playbill_item::del_playbill_item_info_by_time($dc, $dt, $endtime, $video_id);
                }
				error_log("=============6===========\n",'3','test.txt');
				error_log(var_export($list,true)."\n",'3','test.txt');
				
				$start_time  = '';
                foreach ($list as $sql) {
                	error_log("=============7===========\n",'3','test.txt');
                		error_log(var_export($sql,true)."\n",'3','test.txt');
						if(empty($sql['name'])){
							continue;
						}						
						if($g_inject){
							$np_guid_rand = np_guid_rand();
							$xml_str .= '<Object ElementType="Schedule" ID="' .$np_guid_rand. '" Action="REGIST" Code="' .$np_guid_rand. '">';	
							$xml_str .= '<Property Name="ChannelID">'.$video_id.'</Property>';
							$xml_str .= '<Property Name="ChannelCode">'.$video_id.'</Property>';
							
							$item_nns_name = htmlspecialchars($sql['name'], ENT_QUOTES);
							$item_nns_name = htmlspecialchars($item_nns_name, ENT_QUOTES);
							$xml_str .= '<Property Name="ProgramName">'.$item_nns_name.'</Property>';
							$xml_str .= '<Property Name="SearchName">'.htmlspecialchars($sql['pinyin'], ENT_QUOTES).'</Property>';
							$xml_str .= '<Property Name="Genre">Genre</Property>';
							$xml_str .= '<Property Name="StartDate">'.date('Ymd',strtotime($sql['begin_time'])).'</Property>';
							$xml_str .= '<Property Name="StartTime">'.date('His',strtotime($sql['begin_time'])).'</Property>';
							$time_to = timediff($sql['time_len']);
							$xml_str .= '<Property Name="Duration">'.$time_to.'</Property>';
							$xml_str .= '<Property Name="Status">1</Property>';
							$xml_str .= '</Object>';
							$start_time = date('Ymd',strtotime($sql['begin_time']));
						}
                        //if (nl_playbill_item::add_playbill_item($dc, $video_id, $sql)) {
                                $resultnum++;
                        //}
                }
				if($g_inject){
					$xml_str .= '</Objects>';
					$xml_str .= '</ADI>';
					$_GET['sp_id'] = 'jllt';
					//include dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/mgtv_init.php';
					include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/utils.func.php';
					include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/nn_db.class.php';
					include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/jllt/models/c2_task_model.php';
					c2_task_model::add_new_playbill($video_id, $xml_str,$start_time);
					error_log("=============8===========\n",'3','test.txt');
					error_log(var_export($xml_str,true)."\n",'3','test.txt');
				}
        }*/
		
		$resultnum = 0;
		foreach ($live_list as $live_item) {
		  $video_id = $live_item['nns_live_id'];
		  // foreach ($deltime as $dt) {
			// $endtime = date('Ymd', strtotime($dt) + 86400);
			// nl_playbill_item::del_playbill_item_info_by_time($dc, $dt, $endtime, $video_id);
		  // }
// 		
		  foreach ($list as $sql) {
			if (nl_playbill_item::add_playbill_item($dc, $video_id, $sql)) {
			 $resultnum++;
			}
		  }
		 }

        if ($resultnum > 0)
                return 'Success Count : ' . $resultnum;
        else
                return '导入失败';
}




	//eg   3600 to 010000
	function timediff($timediff) 
	{ 
	      // if($begin_time < $end_time){ 
	         // $starttime = $begin_time; 
	         // $endtime = $end_time; 
	      // } 
	      // else{ 
	         // $starttime = $end_time; 
	         // $endtime = $begin_time; 
	      // } 
	      //$timediff = $endtime-$starttime; 
	      $days = intval($timediff/86400); 
	      $remain = $timediff%86400; 
	      $hours = intval($remain/3600); 
	      $remain = $remain%3600; 
	      $mins = intval($remain/60); 
	      $secs = $remain%60;
		  if($days>0){
		  	$hours = $days*24;
		  }
		  if(strlen($hours)==1){
		  	$hours ="0".$hours;
		  }
		  if(strlen($mins)==1){
		  	$mins ="0".$mins;
		  }
		  if(strlen($secs)==1){
		  	$secs ="0".$secs;
		  }
	      //$res = array("hour" => $hours,"min" => $mins,"sec" => $secs); 
	      return $hours.$mins.$secs; 
	}

?>